package com.auoem.radio.common.custview;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentActivity;

import com.auctus.am.framework.entity.Contact;
import com.auctus.am.framework.enums.CallTypeEnums;
import com.auctus.am.framework.utils.LogM;
import com.auoem.radio.R;
import com.auoem.radio.common.filter.EnglishCharFilter;
import com.auoem.radio.common.utils.ResourceUtils;
import com.auoem.radio.databinding.FragmentEditCtDialogBinding;

public class EditCtDialogFragment extends DialogFragment implements View.OnClickListener {

    private final static int MAX_LEN = 200;

    private FragmentEditCtDialogBinding mBinding;
    private OnEditFinishListener mOnEditFinishListener;

    private String mDefaultValue = "";
    private String mTitle = "";
    private int mMaxLength = 20;
    private int mInputType = InputType.TYPE_CLASS_TEXT;

    private String digist;

    private Contact mContact;

    public EditCtDialogFragment() {
    }

    public EditCtDialogFragment(@NonNull String title, String defaultValue) {
        mTitle = title;
        mDefaultValue = defaultValue == null ? "" : defaultValue;
    }

    public EditCtDialogFragment(@NonNull int title, int defaultValue) {
        if (title != 0) {
            mTitle = ResourceUtils.getResourcesString(title);
        }
        if (title != 0) {
            mDefaultValue = ResourceUtils.getResourcesString(defaultValue);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = FragmentEditCtDialogBinding.inflate(inflater, container, false);
        initView();
        return mBinding.getRoot();
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
    }

    private void updateAttr() {
        if (mMaxLength > 0 && mMaxLength < 200) {
//            mBinding.contentEt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(mMaxLength)});
            setFilter();
        }

//        if (!TextUtils.isEmpty(digist)) {
//            mBinding.contentEt.setKeyListener(DigitsKeyListener.getInstance(digist));
//        }
    }

    public void setAttr(int maxLen, String digist) {
        setMaxLength(maxLen);

        if (!TextUtils.isEmpty(digist)) {
            this.digist = digist;
//            mBinding.contentEt.setKeyListener(DigitsKeyListener.getInstance(digist));
        }
    }


    public void setContent(@NonNull Contact contact) {
        if (contact != null) {
            try {
                mContact = contact.clone();
            } catch (CloneNotSupportedException e) {
                mContact = new Contact();
                e.printStackTrace();
            }
        } else {
            mContact = new Contact();
        }
        updateContent();
        LogM.d("setContent: " + mDefaultValue);
    }

    private void updateContent() {
        if (mBinding == null || mContact == null) {
            return;
        }
        switch (mContact.calllType) {
            case IND:
                mBinding.rbInd.setChecked(true);
                mBinding.etId.setEnabled(true);
                break;
            case GRP:
                mBinding.rbGrp.setChecked(true);
                mBinding.etId.setEnabled(true);
                break;
            case ALL:
                mBinding.rbAll.setChecked(true);
                mBinding.etId.setEnabled(false);
                break;
        }

        if (!TextUtils.isEmpty(mContact.name)) {
            mBinding.etName.setText(mContact.name);
        } else {
            mBinding.etName.setText("");
            mBinding.etName.setHint(R.string.hl_ct_name_hint);
        }

        if (mContact.cid > 0) {
            mBinding.etId.setText(mContact.cid + "");
        } else {
            mBinding.etId.setText("");
            mBinding.etId.setHint(R.string.hl_ct_id_hint);
        }
    }

    private void initView() {
        mBinding.cancelButton.setOnClickListener(this);
        mBinding.delButton.setOnClickListener(this);
        mBinding.okButton.setOnClickListener(this);
        mBinding.rbAll.setOnClickListener(this);
        mBinding.rbGrp.setOnClickListener(this);
        mBinding.rbInd.setOnClickListener(this);

        setFilter();
        updateAttr();
        updateContent();
    }

    private Contact getEditContact() {
//        Contact contact = new Contact();
        if (mBinding.rbAll.isChecked()) {
            mContact.calllType = CallTypeEnums.ALL;
        } else if (mBinding.rbGrp.isChecked()) {
            mContact.calllType = CallTypeEnums.GRP;
        } else {
            mContact.calllType = CallTypeEnums.IND;
        }
        mContact.name = mBinding.etName.getText().toString().trim();
        try {
            mContact.cid = Integer.parseInt(mBinding.etId.getText().toString().trim());
        } catch (NumberFormatException e) {
            mContact.cid = -1;//非法ID
            e.printStackTrace();
        }
        return mContact;
    }

    private void setFilter() {
        EnglishCharFilter inputFilterMaxLen = new EnglishCharFilter(mMaxLength);
//        mBinding.contentEt.setFilters(new InputFilter[]{inputFilterMaxLen});
    }

    public void setEditInputType(int type) {
        LogM.d("AAA", "setEditInputType: 1111");
        mInputType = type;
    }

    public void setMaxLength(int maxLength) {
//        mMaxLength = maxLength;
        mMaxLength = Math.max(maxLength, 0);
        mMaxLength = Math.min(mMaxLength, MAX_LEN);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            //TODO:连续点击某处会使getActivity()为空导致应用崩溃
            //Hack:1 trycatch, 2 if null
            FragmentActivity fActivity = getActivity();
            if (fActivity == null)
                return;
            mBinding.etId.requestFocus();
//            KeyboardManager.showInputKeyboard(getActivity().getApplicationContext(), mBinding.contentEt);
        }, 300);
    }

    public void setOnEditFinishListener(OnEditFinishListener onEditFinishListener) {
        mOnEditFinishListener = onEditFinishListener;
    }

    @Override
    public void onClick(View v) {
        if (v == mBinding.cancelButton) {
            dismiss();
        } else if (v == mBinding.delButton) {
            if (mOnEditFinishListener != null) {
                mOnEditFinishListener.onFinished(2, getEditContact());
            }
            dismiss();
        } else if (v == mBinding.okButton) {
            if (mOnEditFinishListener != null) {
                mOnEditFinishListener.onFinished(1, getEditContact());
            }
            dismiss();
        } else if (v == mBinding.rbAll) {
            mBinding.etId.setText("16777215");
            mBinding.etId.setEnabled(false);
        } else if (v == mBinding.rbGrp) {
            mBinding.etId.setEnabled(true);
            mBinding.etId.setText("");
        } else if (v == mBinding.rbInd) {
            mBinding.etId.setEnabled(true);
            mBinding.etId.setText("");
        }
    }

    public interface OnEditFinishListener {
        void onFinished(int opt, Contact contact);
    }

}
